package br.edu.ifrn.servlets;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import br.edu.ifrn.beans.Admin;
import br.edu.ifrn.persistencia.AdminDAO;

public class EditarAdmin extends HttpServlet {
	private static final long serialVersionUID = 1L;
	HttpSession sessao;

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
	}

	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		sessao = req.getSession();
		sessao.removeAttribute("erro");
		editarsenha(req, resp);
	}

	private void editarsenha(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		AdminDAO dao = new AdminDAO();
		Admin adminApp = (Admin) sessao.getAttribute("admin");
		Admin adminBanco = dao.recuperarPorMatricula(adminApp.getMatricula());
		
		if (adminBanco.getSenha().equals(req.getParameter("antiga"))) {
			if (req.getParameter("nova1").equals(req.getParameter("nova2"))) {
				adminBanco.setSenha(req.getParameter("nova1"));
				sessao.setAttribute("admin", adminBanco);
				dao.editarSenha(adminBanco);
				String mensagem = "Senha alterada com sucesso";
				sessao.setAttribute("mensagem", mensagem);
				RequestDispatcher jsp = req.getRequestDispatcher("admins.jsp");
				jsp.forward(req, resp);
			} else {
				String erro = "Novas senhas digitadas diferentes";
				sessao.setAttribute("erro", erro);
				RequestDispatcher jsp = req
						.getRequestDispatcher("editarsenhaadmin.jsp");
				jsp.forward(req, resp);
			}

		} else {
			String erro = "Senha incorreta";
			sessao.setAttribute("erro", erro);
			RequestDispatcher jsp = req.getRequestDispatcher("editarsenhaadmin.jsp");
			jsp.forward(req, resp);
		}
	}
}
